<template>
  <view class="content">
    <view class="head">
      <u-navbar leftIcon="arrow-leftward" :placeholder='true' @leftClick="leftClick" title="訂單信息">
      </u-navbar>
    </view>
    <view class="examine" v-if="examine>0">
      <view class="e-l">
        審核狀態：
      </view>
      <view class="e-r" style="flex: 1">
        <view v-if="examine===4">可申請修改</view>
        <view v-else-if="examine==2">可修改內容</view>
        <view v-else>
          <picker @change="bindPickerChange" :value="activeindex" :range="statusOptions" range-key="label">
            <view class="picker" style="display: flex;justify-content: space-between">
              <view class="uni-input">{{ statusOptions[activeindex] ? statusOptions[activeindex].label : '' }}</view>
              <u-icon size="28rpx" name="arrow-right"></u-icon>
            </view>
          </picker>
        </view>
        <!-- 审核员操作部分 -->
      </view>
    </view>
    <view class="examine" v-if="[1,2,3,4].includes(examine)">
      <view class="e-l">
        處理說明：
      </view>
      <view class="e-r" style="flex: 1">
        <input v-model="explain" placeholder="請輸入處理說明">
        <!-- 审核员操作部分 -->
      </view>
    </view>
    <view class="address">
      <view class="top">
        <text class="name">{{ order.consignee }}</text>
        <text style="margin-left: 24rpx;">{{ order.mobile }}</text>
      </view>
      <view class="bottom">
        <text>{{ order.address }}</text>
      </view>
    </view>
    <view class="dindan">
      <view class="dindan-no">
        <view class="no-l">
          {{ order.order_sn }}
        </view>
        <view class="no-r">
          <view v-if="order.pay_status == 40">
            已退款
          </view>
          <view v-else-if="order.status!=null && order.order_status==0">
            {{ order.status | status }}
          </view>
          <view v-else-if="order.pay_status">
            {{ order.pay_status| pay_status }}
          </view>
          <view v-else>
            {{ order.order_status | orstatus }}
          </view>
        </view>
      </view>
      <view class="">
        <view class="goods-detail" v-for="(item,index) in goods" :key="index" @click="$store.dispatch('toDetails',item.goods_id)">
          <view class="detail-left">
            <view class="goods-left">
              <view class="goods-img">
                <image :src="getFirstImageLink(item.goods_images)" mode="aspectFit"></image>
                <!-- <image :src="item.goodsImage" style="width: 150rpx;height: 140rpx;"></image> -->
              </view>
            </view>
            <view class="size">
              <view class="goods-title">{{ item.goods_name }}</view>
              <view class="center">
                <text>{{ item.attr_value }}</text>
                <text>x{{ item.goods_number }}</text>
              </view>
              <view class="bottom">
                <text class="goods-price">MOP {{ item.unit_price }}</text>
                <view class="detail-right">
                </view>
              </view>
            </view>
          </view>
        </view>
        <view class="jiage">
          <view>
            共
            <text style="color:#645AED ;">{{ getTotalGoodsNumber(goods) }}</text>
            件，合計：
            <text
                style="color:#645AED ;">MOP {{ order.order_amount }}
            </text>
          </view>
          <view class="">
            折後價格：
            <text style="color:#645AED ;">MOP {{ order.order_amount }}</text>
          </view>
        </view>

      </view>
    </view>
    <view class="details" style="padding-bottom: 144rpx;">
      <view class="details-item">
        <view>用戶名</view>
        <view>{{ order.userID }}</view>
      </view>
      <view class="details-item">
        <view>下單時間</view>
        <view>{{ order.createtime }}</view>
      </view>
      <view class="details-item">
        <view>所屬部門</view>
        <view>{{ order.departmentname }}</view>
      </view>
      <view class="details-item">
        <view>客戶備註</view>
        <view>{{ order.postscript || '暫無' }}</view>
      </view>
      <view class="details-item">
        <view>簽收圖片</view>
        <image v-if="order.sign_picture" @click="previewImage(order.sign_picture)" class="item-img"
               :src="order.sign_picture" mode=""></image>
        <view v-else>暫無</view>

      </view>
      <view class="details-item">
        <view>PDF底單</view>
        <!-- <view>{{order.PDF_bottom_sheet || '暫無'}}</view> -->
        <view style="color:#0984fe " v-if="order.PDF_bottom_sheet" @click="downloadpdf(order.PDF_bottom_sheet)">下载
        </view>
        <!--				<image v-if="order.PDF_bottom_sheet" @click="previewImage(order.PDF_bottom_sheet)" class="item-img" :src="order.PDF_bottom_sheet" mode=""></image>-->
        <view v-else>暫無</view>
      </view>
      <view class="details-item" style="flex-direction: column;">
        <view>流程說明</view>
        <view class="">
          <u-steps direction="column" activeColor="#999999" inactiveColor="#999999">
            <u-steps-item v-for="(item,index) in log" :key="index" :title="item.content || '無'"
                          :desc="item.end_time">
            </u-steps-item>

          </u-steps>
        </view>
      </view>
    </view>
    <view class="threebtn">
      <view class="btn" @click="refund">
        申請退貨
      </view>
      <view class="btn" @click="cancel">
        申請取消
      </view>
      <view class="btn green" @click="againorder">
        再次下單
      </view>
      <view class="btn green" v-if="examine > 0" @click="submitExamine">
        <span v-if="[1,3].includes(examine)">提交審核狀態</span>
        <span v-if="examine == 2">提交訂單</span>
        <span v-if="examine == 4">申請修改</span>
      </view>
    </view>
    <!-- 申请退款弹窗 -->
    <u-popup :show="refundshow" :round="10" :closeable='true' mode="bottom" @close="closeWindows" @open="open">
      <view class="refund-dialog">
        <view class="title">
          申請退貨
        </view>
        <!-- <view class="text-box"> -->
        <view class="tuihuo">
					<textarea class="text-box" v-model="refundfrom.pay_note"
                    placeholder-style="padding:32rpx ;font-size: 28rpx;font-family: PingFang SC;font-weight: 500;color: #999999;"
                    maxlength='200' placeholder="請輸入退貨說明">
					</textarea>
          <view class="max-input">
            {{ refundfrom.pay_note.length }}/200
          </view>
        </view>
        <view class="btn" @click="returnsub">
          提交
        </view>
      </view>
    </u-popup>
  </view>
</template>

<script>
import {
  myorders,
  returngood,
  cancelgood,
  orderdetils,
  againcart, submitcheck
} from '@/network/api/user.js';
import download from "@/pages/mine/download/index.vue";
import {baseURL} from "@/network/base";

export default {
  computed: {
    download() {
      return download
    },
    statusOptions() {
      let options = [];
      if (this.examine == 1) {
        options = this.examine_options;
      } else if (this.examine == 3) {
        options = this.modify_options;
      }
      return options;
    }
  },
  data() {
    return {
      explain: "",
      select_status: '',
      activeindex: null,
      examine_options: [{
        value: 0,
        label: '通過審核'
      },
        {
          value: 1,
          label: '不通過'
        },
      ], //审核选项
      modify_options: [{
        value: 0,
        label: '同意申請'
      },
        {
          value: 1,
          label: '不同意'
        },
      ], //申请修改选项
      examine: -1,
      refundshow: false,
      refundfrom: {
        order_id: '',
        pay_note: ''
      },
      goods: [],
      orderid: '',
      order: {},
      log: [],
    }
  },
  filters: {
    // 列表订单状态过滤器
    status(
        val,
    ) {
      switch (val) {
        case 0:
          return '未審批'
          break;
        case 1:
          return '已審批'
          break;
        case 2:
          return '申請修改'
          break;
        case 3:
          return '取消訂單'
          break;
        case 4:
          return '未通過'
          break;
      }
    },
    orstatus(
        val,
    ) {
      switch (val) {
        case '0':
          return '無需審批'
          break;
        case '1':
          return '未付款'
          break;
        case '2':
          return '已付款'
          break;
        case '3':
          return '已確認收貨'
          break;
        case '4':
          return '已發貨'
          break;
        case '5':
          return '已退貨'
          break;
        case '6':
          return '全單取消'
          break;
        case '7':
          return '要求退貨'
          break;
        case '8':
          return '已退貨'
          break;
      }
    },
    pay_status(val) {
      switch (val) {
        case '0':
          return '待付款'
          break;
        case '10':
          return '逾期'
          break;
        case '20':
          return '已全數支付'
          break;
        case '30':
          return '已部分支付'
          break;
      }
    }
  },

  onLoad(e) {
    console.log(e.orderid);
    if (e.orderid) {
      this.orderid = e.orderid
    }
    this.getdetils()
  },
  methods: {
    async submitExamine() {
      let data = {
        order_id: this.order.order_id,
        status: this.select_status,
        remark: this.explain
      }
      let url = ''
      if (this.examine == 1) {
        url = '/orderstatus/implement';
      } else {
        url = '/orderstatus/allow';
      }
      //提交中
      uni.showLoading({
        title: "提交中，请稍后...",
        mask: true,
      });
      const res = await submitcheck(url, data)
      uni.hideLoading()
      console.log(res)
      await this.getdetils()
    },
    bindPickerChange(e) {
      this.activeindex = e.detail.value
      this.select_status = this.statusOptions[e.detail.value].value
      console.log(this.select_status)
    },
    downloadpdf(pdf) {
      console.log(pdf)
      const pdfUrl = pdf
      // #ifdef H5
      window.open(
          pdfUrl
      )
      // #endif
      // 微信下载文件需要在微信公众平台>开发>开发管理>服务器域名>downloadFile合法域名>配置白名单域名
      // #ifdef MP-WEIXIN
      uni.downloadFile({
        url: pdfUrl,
        success: res => {
          console.log(res)
          if (res.statusCode === 200) {
            // 预览pdf文件
            uni.openDocument({
              filePath: res.tempFilePath,
              showMenu: true, // 右上角菜单，可以进行分享保存pdf
              success: function (file) {
                console.log("file-success", file)
              }
            })
          }
        }
      })
      // #endif
      // #ifdef APP-PLUS
      uni.showLoading({
        title: '正在下载……'
      });
      uni.downloadFile({
        url: pdfUrl,
        success: res => {
          console.log(res)
          if (res.statusCode === 200) {
            // 保存pdf文件至手机，一般安卓端存储路径为：手机存储/dcim/camera文件夹下
            uni.hideLoading()
            uni.saveFile({
              tempFilePath: res.tempFilePath,
              success: function (res) {
                uni.showToast({
                  icon: 'success',
                  mask: true,
                  // title: '文件已保存：' + res.savedFilePath, //保存路径
                  title: '下载成功',
                  duration: 2000,
                });
                setTimeout(() => {
                  var filePath = res.savedFilePath;
                  uni.openDocument({ //新开页面打开文档，支持格式：doc, xls, ppt, pdf, docx, xlsx, pptx。
                    filePath: filePath,
                    showMenu: true,
                    success: function (res) {
                      console.log('打开文档成功');
                    }
                  });
                }, 1000)
              }
            })
          }
        },
        fail: (err) => {
          console.log(err);
          uni.showToast({
            icon: 'none',
            mask: true,
            title: '文件下载失败',
          });
        },
      })
      // #endif
    },
    //uniapp预览单张图片方法
    previewImage(url) {
      uni.previewImage({
        urls: [url],
        longPressActions: {
          itemList: ['发送给朋友', '保存图片', '收藏'],
        },
      });
    },
    closeWindows() {
      this.refundshow = false
    },
    open() {

    },
    refund() {
      this.refundshow = true
      this.refundfrom.order_id = this.order.order_id
    },
    async cancel() {
      let data = {
        order_id: this.order.order_id,
        cancel_note: '',
      }
      uni.showLoading({
        title: "提交中，请稍后...",
        mask: true,
      });
      const res = await cancelgood(data)
      if (res.data.code == 1) {
        uni.hideLoading()
        uni.showToast({
          title: "提交申请成功，请耐心等待",
          icon: 'success',
        });
      } else {
        uni.hideLoading()
      }

    },
    async againorder() {
      const from = this.goods.map(item => {
        return {
          rec_id: item.rec_id,
          order_id: item.order_id,
          goods_number: item.goods_number,
          goods_id: item.goods_id,
          goods_images: item.goods_images,
          goodnumber: item.goodnumber,
          numbering: item.numbering,
          goods_sn: item.goods_sn,
          specification_numbering: item.specification_numbering
        }
      })
      let data = {
        goods: from,
        lang: 'cn',
        order_sn: this.order.order_sn,
      }
      console.log(data);
      const res = await againcart(data)
      if (res.data.code == 1) {
        uni.showToast({
          title: '加入購物車成功',
          icon: 'success',
          duration: 2000
        })
      }
      console.log(res);
    },
    async returnsub() {
      uni.showLoading({
        title: "提交中，请稍后...",
        mask: true,
      });
      const res = await returngood(this.refundfrom)
      if (res.data.code == 1) {
        uni.hideLoading()
        uni.showToast({
          title: "提交申请成功，请耐心等待",
          icon: 'success',
        });
        this.refundfrom.pay_note = ''
        this.refundshow = false
      } else {
        uni.hideLoading()
        this.refundfrom.pay_note = ''
        this.refundshow = false
      }
    },
    getTotalGoodsNumber(item) {
      // 计算商品总数量
      return item.reduce((total, goods) => total + goods.goods_number, 0);
    },
    // getTotalPrice(item) {
    // 	// 计算总价格
    // 	const totalPrice = item.reduce((total, goods) => total + goods.goods_price * goods.goods_number, 0);
    // 	return totalPrice.toFixed(2);
    // },
    async getdetils() {
      let data = {
        id: this.orderid
      }
      const res = await orderdetils(data)
      this.goods = res.data.goods
      this.order = res.data.order
      this.log = res.data.log
      this.examine = res.data.respon === undefined ? -1 : res.data.respon

    },
    leftClick(url) {
      // uni.navigateTo({
      // 	url: '/pages/mine/order/index',
      // })
      uni.navigateBack({
        delta: 1
      })
    }
  },

}
</script>

<style lang="scss">
page {

  background: #F5F6F9;
}

.examine {
  display: flex;
  align-items: center;
  padding: 32rpx;
  background-color: #fff;
}

.refund-dialog {
  height: 900rpx;
  display: flex;
  flex-direction: column;
  align-items: center;

  .btn {
    position: fixed;
    bottom: 16rpx;
    width: 686rpx;
    height: 80rpx;
    background: #645AED;
    border-radius: 30rpx;
    text-align: center;
    line-height: 80rpx;
    font-size: 32rpx;
    font-family: PingFang SC;
    font-weight: bold;
    color: #FFFFFF;
  }

  .title {

    margin-top: 44rpx;
    font-size: 32rpx;
    font-family: PingFang SC;
    font-weight: bold;
    color: #333333;
  }

  .tuihuo {
    position: relative;
    width: 686rpx;
    min-height: 316rpx;
    margin: 60rpx auto;

    .text-box {
      width: 686rpx;
      height: 316rpx;
      border-radius: 20rpx;
      background: #F7F7F7;
    }

    .max-input {
      position: absolute;
      bottom: 20rpx;
      right: 32rpx;
      font-size: 24rpx;
      font-family: PingFang SC;
      font-weight: 500;
      color: #333333;
    }
  }


}

.content {
  position: relative;
  height: 100vh;

  .details {
    margin-top: 16rpx;
    background-color: white;
    padding: 32rpx;

    .details-item {
      margin-bottom: 24rpx;
      font-size: 28rpx;
      font-family: PingFang SC;
      font-weight: 500;
      color: #999999;
      display: flex;
      justify-content: space-between;

      .item-img {
        width: 178rpx;
        height: 178rpx;
        background-color: bisque;
      }
    }
  }

  .threebtn {
    width: 100vw;
    height: 110rpx;
    bottom: 0;
    background: #FFFFFF;
    border-radius: 0rpx;
    position: fixed;
    display: flex;
    justify-content: flex-end;
    align-items: center;
    font-size: 28rpx;
    font-family: PingFang SC;
    font-weight: 500;
    color: #333333;

    .btn {
      margin-right: 20rpx;
      text-align: center;
      line-height: 60rpx;
      padding: 0 15rpx;
      height: 60rpx;
      border: 1rpx solid #CBCBCB;
      border-radius: 20rpx;
    }

    .green {

      border: 1rpx solid #645AED;
      color: #645AED;
    }
  }

  .jiage {
    display: flex;
    flex-direction: column;
    justify-content: flex-end;
    align-items: flex-end;
    margin-top: 22rpx;
    font-size: 28rpx;
    font-family: PingFang SC;
    font-weight: bold;
  }

  .dindan {
    margin-top: 16rpx;
    background: white;
    padding: 32rpx;

    .dindan-no {
      height: 84rpx;
      border-bottom: 1rpx solid #F1F1F1;
      display: flex;
      justify-content: space-between;
      font-size: 28rpx;
      font-family: PingFang SC;
      font-weight: 500;

      .no-l {
        color: #3A3A3A;
      }

      .no-r {
        color: #645AED
      }
    }

    .goods {
      line-height: 80rpx;
      background-color: #FFFFFF;

      &-detail {
        display: flex;
        padding: 16rpx 0;
        // margin: 0 32rpx;
        background-color: #fff;
        justify-content: space-between;
        align-items: center;

        .detail-left {
          flex: 1;
          display: flex;

          .goods-left {
            display: flex;
            align-items: center;

            .goods-img {
              width: 180rpx;
              height: 180rpx;
              background: #FFFFFF;
              border: 1rpx solid #DEDEDE;
              border-radius: 30rpx;
              display: flex;
              justify-content: center;
              align-items: center;

              image {
                max-width: 90%;
                max-height: 90%;
              }
            }
          }
        }

        .size {
          flex: 1;
          display: flex;
          justify-content: space-between;
          flex-direction: column;
          margin-left: 30rpx;

          .center {
            justify-content: space-between;
            display: flex;
            font-size: 22rpx;
            font-family: PingFang SC;
            font-weight: 500;
            color: #999999;
            margin-top: 8rpx;
          }

          .bottom {
            margin-top: 22rpx;
            display: flex;
            align-items: center;
            justify-content: space-between
          }

          .goods-title {
            font-size: 28rpx;
            font-family: PingFang SC;
            font-weight: 500;
            color: #333333;
          }

          .goods-price {
            font-size: 28rpx;
            font-family: PingFang SC;
            font-weight: bold;
            color: #4949C3;
          }
        }

        .detail-right {
          .stepper {
            display: flex;
            // align-items: center;
            vertical-align: middle;

            .stepper-value {
              margin: 0 20rpx;
              font-size: 24rpx;
              line-height: 43rpx;
              font-family: PingFang SC;
              font-weight: 500;
              color: #333333;
            }

            .stepper-btn {
              image {
                width: 44rpx;
                height: 44rpx;
              }
            }
          }

          text {
            width: 50rpx;
            line-height: 50rpx;
            text-align: center;
            display: inline-block;
            background-color: #F7F7F7;
            margin-right: 10rpx;
          }

          .add {
            color: #FA4305;
            border-radius: 10rpx 30rpx 30rpx 10rpx;
            margin-right: 20rpx;
          }

          .subtract {
            border-radius: 30rpx 10rpx 10rpx 30rpx;
          }
        }
      }
    }

  }

  .address {
    padding: 32rpx;
    background-color: white;
    margin-top: 16rpx;
    font-size: 28rpx;
    font-family: PingFang SC;
    font-weight: bold;
    color: #333333;

    .bottom {

      font-weight: 500;
    }
  }
}
</style>
